package com.xindaoapp.happypet.activity;

import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.PetInfo;
import com.xindaoapp.happypet.bean.PetInfo.Pet;
import com.xindaoapp.happypet.ui.BaseActivity;
import com.xindaoapp.happypet.utils.BitmapUtil;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.CircleImageView;

// public class MyLoveActivity extends BaseLoadAnimationAcitivity implements OnClickListener {
public class MyLoveActivity extends BaseActivity implements OnClickListener {
    // @ViewInject(R.id.tittle_common_cancel)
    // private ImageView tittle_common_cancel;
    // @ViewInject(R.id.tittle_common_content)
    // private TextView tittle_common_content;

    @ViewInject(R.id.mylove_list)
    private ListView mylove_list;
    // @ViewInject(R.id.no_pet)
    // private ImageView no_pet;


    private MyLoveAdapter adapter;

    // @Override
    // protected void onCreate(Bundle savedInstanceState) {
    // setContentView(R.layout.activity_mylove);
    // super.onCreate(savedInstanceState);
    //
    // }

    @Override
    protected void initViews() {
        // TODO Auto-generated method stub
        super.initViews();
        ViewUtils.inject(this);
        initListView();
        initClick();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    @Override
    protected void onLoadDatas() {
        // TODO Auto-generated method stub
        super.onLoadDatas();
        loadData();
    }

    private void initListView() {
        View v = View.inflate(this, R.layout.button, null);
        mylove_list.addFooterView(v);
        mylove_list.setAdapter(null);
        Button mylove_addpet = (Button) v.findViewById(R.id.mylove_addpet);
        mylove_addpet.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyLoveActivity.this, AddPetActivity.class);
                intent.putExtra("petid", "");
                intent.putExtra("petname", "");
                intent.putExtra("petpic", "");
                startActivity(intent);
            }
        });
    }

    private List<Pet> pets;
    private boolean isFirst = true;

    private void loadData() {
        RequestParams params = new RequestParams();
        params.put("uid", UserState.getUserUid());
        AddClient.post(Address.PETLIST, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                super.onSuccess(statusCode, content);
                isFirst = false;
                try {
                    PetInfo info = JSON.parseObject(content, PetInfo.class);
                    // onDataArrived(true);
                    if (info.getArray().size() > 0) {
                        pets = info.getArray();
                        adapter = new MyLoveAdapter(pets);
                        mylove_list.setAdapter(adapter);
                    } else {
                        // onDataArrivedEmpty();
                    }
                } catch (Exception e) {
                }
            }



            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                // onDataArrived(false);
            }
        });
    }

    @SuppressWarnings("unused")
    private class MyLoveAdapter extends BaseAdapter {
        private List<Pet> arrays;

        public List<Pet> getArrays() {
            return arrays;
        }

        public void setArrays(List<Pet> arrays) {
            this.arrays = arrays;
        }

        public MyLoveAdapter(List<Pet> arrays) {
            super();
            this.arrays = arrays;
        }

        @Override
        public int getCount() {
            return arrays.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(MyLoveActivity.this, R.layout.mylove_list_item, null);
                holder = new ViewHolder();
                holder.pet_img = (CircleImageView) convertView.findViewById(R.id.pet_img);
                holder.pet_name = (TextView) convertView.findViewById(R.id.pet_name);
                holder.pet_sex = (TextView) convertView.findViewById(R.id.pet_sex);
                holder.pet_zhonglei = (TextView) convertView.findViewById(R.id.pet_zhonglei);
                holder.pet_pinzhong = (TextView) convertView.findViewById(R.id.pet_pinzhong);
                holder.pet_birthrday = (TextView) convertView.findViewById(R.id.pet_birthrday);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.pet_name.setText(arrays.get(position).getTitle());
            if (arrays.get(position).getSex().equals("1")) {
                holder.pet_sex.setText("公");
            }
            if (arrays.get(position).getSex().equals("2")) {
                holder.pet_sex.setText("母");
            }
            if (arrays.get(position).getPettype().equals("1")) {
                holder.pet_zhonglei.setText("汪星人");
            }
            if (arrays.get(position).getPettype().equals("2")) {
                holder.pet_zhonglei.setText("喵星人");
            }
            if (arrays.get(position).getPettype().equals("3")) {
                holder.pet_zhonglei.setText("小宠星人");
            }
            if (arrays.get(position).getPettype().equals("4")) {
                holder.pet_zhonglei.setText("水星人");
            }
            holder.pet_pinzhong.setText(arrays.get(position).getBreed());

            if (!TextUtils.isEmpty(arrays.get(position).birth)) {
                holder.pet_birthrday.setText(arrays.get(position).birth);
            } else {
                holder.pet_birthrday.setText("暂无数据");
            }

            ImageLoader.getInstance().displayImage(arrays.get(position).getCover(), holder.pet_img,
                    BitmapUtil.getPetLoading());

            // if (!arrays.get(position).getCover().equals("")
            // && arrays.get(position).getCover() != null) {
            // BitmapDisplayConfig config = new BitmapDisplayConfig();
            // config.setLoadingDrawable(getResources().getDrawable(R.drawable.pet_touxiang));
            // BitmapHelp.getBitmapUtils(getApplicationContext()).display(holder.pet_img,
            // arrays.get(position).getCover() + "?" + Math.random(), config);
            // // ImageLoader.getInstance().displayImage(arrays.get(position).getCover()+"?"+
            // // Math.random(),holder.pet_img,
            // // new
            // } else {
            // // holder.pet_img.setImageResource(R.drawable.person_loading);
            // }
            return convertView;
        }
    }

    private class ViewHolder {
        CircleImageView pet_img;
        TextView pet_name;
        TextView pet_sex;
        TextView pet_zhonglei;
        TextView pet_pinzhong;
        TextView pet_birthrday;
    }

    private void initClick() {
        // tittle_common_content.setText("我的爱");
        // tittle_common_cancel.setOnClickListener(this);
        mylove_list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MyLoveActivity.this, AddPetActivity.class);
                intent.putExtra("isfrom", "change");
                intent.putExtra("petid", pets.get(position).getId());
                intent.putExtra("petname", pets.get(position).getTitle());
                intent.putExtra("petpic", pets.get(position).getCover());
                intent.putExtra("pet", pets.get(position));
                startActivity(intent);

            }
        });
        mylove_list.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                position1 = position;
                // showDialog();
                new AlertDialog.Builder(MyLoveActivity.this).setTitle("删除").setMessage("确认要删除宠物吗?")
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                deletePet(position1);
                                dialog.dismiss();
                            }
                        }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {}
                        }).create().show();
                return true;
            }
        });
    }

    private int position1;
    private TextView textView1;
    private TextView textView2;
    private AlertDialog dialog;

    protected void showDialog() {
        AlertDialog.Builder builder = new Builder(this);
        View view = View.inflate(MyLoveActivity.this, R.layout.delete_pet, null);
        textView1 = (TextView) view.findViewById(R.id.textView1);
        textView2 = (TextView) view.findViewById(R.id.textView2);

        textView1.setOnClickListener(MyLoveActivity.this);
        textView2.setOnClickListener(MyLoveActivity.this);

        dialog = builder.create();
        dialog.setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
            }
        });
        dialog.setView(view);
        dialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        // case R.id.tittle_common_cancel:
        // finish();
        // break;
            case R.id.textView1:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                }).start();
                break;
            case R.id.textView2:
                deletePet(position1);
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                break;
            default:
                break;
        }
    }

    private void deletePet(int position) {
        RequestParams params = new RequestParams();
        params.put("uid", UserState.getUserUid());
        params.put("petid", pets.get(position1).getId());
        AddClient.get(Address.DELETEPET, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    Toast.makeText(getApplicationContext(), "删除成功", Toast.LENGTH_SHORT).show();
                    pets.remove(position1);
                    adapter.notifyDataSetChanged();
                    // loadData();

                    // 初始化宠物列表
                    HappyPetApplication.get().getMoccaApi()
                            .getMyPetList(UserState.getUserUid(), new IRequest<PetInfo>() {

                                @Override
                                public void request(PetInfo t) {
                                    UserState.setPetInfo(t);
                                }
                            });

                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {

                super.onFailure(error, content);
                Toast.makeText(getApplicationContext(), "删除失败", Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected int getContentViewResId() {
        // TODO Auto-generated method stub
        return R.layout.activity_mylove;
    }

    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }


    @Override
    protected String getTopBarTitleStrRes() {
        return "我的爱";
    }

    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                finish();
            }
        };
    }
}
